//
//  Extensions.swift
//  CatPomodoroTimer
//
//  Created by Xuri Li on 2024/8/1.
//

import SwiftUI
import UIKit

extension Color {
    init(hex: UInt, alpha: Double = 1.0) {
        self.init(
            .sRGB,
            red: Double((hex >> 16) & 0xff) / 255.0,
            green: Double((hex >> 8) & 0xff) / 255.0,
            blue: Double(hex & 0xff) / 255.0,
            opacity: alpha
        )
    }
    
    init(hexString: String, alpha: Double = 1.0) {
        var formattedHex = hexString
        
        // 如果十六进制字符串以 # 开头，移除它
        if formattedHex.hasPrefix("#") {
            formattedHex.remove(at: formattedHex.startIndex)
        }
        
        // 将十六进制字符串转换为整数
        if let hexValue = Int(formattedHex, radix: 16) {
            self.init(hex: UInt(hexValue), alpha: alpha)
        } else {
            // 如果无法转换，使用默认颜色
            self.init(.sRGB, red: 1.0, green: 1.0, blue: 1.0, opacity: 1.0)
        }
    }
}

extension UIColor {
    convenience init(hex: UInt, alpha: CGFloat = 1.0) {
        let red = CGFloat((hex >> 16) & 0xFF) / 255.0
        let green = CGFloat((hex >> 8) & 0xFF) / 255.0
        let blue = CGFloat(hex & 0xFF) / 255.0
        
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    convenience init(hexString: String, alpha: CGFloat = 1.0) {
        var formattedHex = hexString
        
        // 如果十六进制字符串以 # 开头，移除它
        if formattedHex.hasPrefix("#") {
            formattedHex.remove(at: formattedHex.startIndex)
        }
        
        // 将十六进制字符串转换为整数
        if let hexValue = Int(formattedHex, radix: 16) {
            self.init(hex: UInt(hexValue), alpha: alpha)
        } else {
            // 如果无法转换，使用默认颜色
            self.init(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        }
    }
}
